
const MOD_NUMBER = 1e5 + 7;

const reduceArray = <T>(keyList: Array<keyof T>, data: T[]) => {
  const hashlist = keyList.length > 0 ? keyList : Object.keys(data) as Array<keyof T>;
  const map: { [key: number]: T } = {};
  
  data.forEach(item => {
    let cum = 0;
    hashlist.forEach((key) => {
      cum = (hash(item[key]) + cum) % MOD_NUMBER;
    });

    if (map[cum]) {
      // 可能是冲突的处理

    } else {
      map[cum] = item;
    }
  });

  return (Object.keys(map) as unknown as number[]).map(hash => map[hash]);
}

/**
 * 
 * @param str 需要被hash的字符串
 */
const hash = (str: any): number => {
  if ( typeof str === 'number' ) {
    return str % MOD_NUMBER;
  } else if ( typeof str === 'string' ) {
    let sum = 0;
    for (let i = 0, h = str.length ; i < h ; ++i ) {
      sum = (str.charCodeAt(i) + sum) % MOD_NUMBER;
    }
    return sum;
  } else {
    return 0;
  }
}

export default reduceArray;
